import config from "@/pages_temp/utils/config.js"
import tools from "@/pages_temp/utils/tools.js"

const baseUrl = "http://192.168.1.29:9501/api/v1/"

// 封装 uni.request
export default {
	config: {
		baseUrl: baseUrl,
		header: {},
		reqCheck: true,
		respCheck: true,
		loading: true,
	},
	resetConfig() {
		this.config.reqCheck = true
		this.config.respCheck = true
		this.config.loading = true
	},
	interceptor: {
		request() {
			if (!tools.getToken()) {
				uni.showToast({
					title: "用户失效",
					icon: "error"
				})
				uni.reLaunch({
					url: config.indexUrl
				})
			}
		},
		response(res) {
			if (res.statusCode === 200) {
				if (res.data.code === 20000) {
					return Promise.resolve(res.data.data)
				} else {
					uni.showToast({
						icon: "error",
						title: "系统错误",
					})
					return Promise.reject(res.data)
				}
			} else if (res.statusCode === 504) {
				uni.showToast({
					icon: "error",
					title: "用户信息已失效",
				})
				tools.setToken()
				uni.reLaunch({
					url: config.indexUrl
				})
				return Promise.reject(res.data)
			} else {
				uni.showToast({
					icon: "error",
					title: "系统错误！",
				})
				return Promise.reject(res.data)
			}
		}
	},
	request(url, method, data) {
		return new Promise((resolve, reject) => {
			if (this.config.loading === true) {
				uni.showLoading({
					title: '易公加载中'
				})
			}
			if (method === 'POST') {
				this.config.header['content-type'] = 'application/json'
			}
			if (this.config.reqCheck) {
				this.interceptor.request()
			}
			this.config.header[config.headerTokenKey] = tools.getToken()
			uni.request({
				url: this.config.baseUrl + url,
				header: this.config.header,
				method,
				data,
			}).then((res) => {
				if (this.config.loading === true) {
					uni.hideLoading()
				}
				if (this.config.respCheck) {
					const a = this.interceptor.response(res).then(res => {
						resolve(res)
					}).catch(e => {
						reject(e)
					})
				} else {
					resolve(res)
				}
			}).catch((err) => {
				console.error(err);
				reject(err)
			});
		})
	},
	get(url, params) {
		return this.request(url, 'GET', params)
	},
	post(url, data) {
		return this.request(url, 'POST', data)
	}
}
